<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>秒杀活动</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center p-4">
<div class="bg-white rounded-lg shadow-lg p-8 max-w-md w-full">
    <h1 class="text-2xl font-bold text-center mb-6">限时秒杀</h1>

    <div class="mb-6 border-b pb-4">
        <img src="https://picsum.photos/400/200" alt="秒杀商品图片" class="w-full h-48 object-cover rounded mb-4">
        <h2 class="text-xl font-semibold">超值商品秒杀</h2>
        <p class="text-red-500 text-2xl font-bold mt-2">¥99.00</p>
        <p class="text-gray-500 line-through">原价: ¥199.00</p>
    </div>

    <div id="status-container" class="text-center mb-6">
        <p id="status-message" class="text-gray-600">点击下方按钮参与秒杀</p>
        <div id="loading" class="hidden mt-4">
            <i class="fa fa-spinner fa-spin text-blue-500 text-2xl"></i>
            <p class="mt-2 text-blue-500">正在抢购中...</p>
        </div>
        <div id="success" class="hidden mt-4">
            <i class="fa fa-check-circle text-green-500 text-2xl"></i>
            <p id="success-message" class="mt-2 text-green-500"></p>
        </div>
        <div id="fail" class="hidden mt-4">
            <i class="fa fa-times-circle text-red-500 text-2xl"></i>
            <p id="fail-message" class="mt-2 text-red-500"></p>
        </div>
    </div>

    <button id="seckill-btn" class="w-full bg-red-500 hover:bg-red-600 text-white py-3 px-4 rounded-lg transition duration-300 font-semibold">
        立即抢购
    </button>
</div>

<script>
    // 模拟用户ID和商品ID
    const userId = 10001; // 实际应用中应从登录信息获取
    const goodsId = 1001; // 秒杀商品ID

    // DOM元素
    const seckillBtn = document.getElementById('seckill-btn');
    const statusMessage = document.getElementById('status-message');
    const loading = document.getElementById('loading');
    const success = document.getElementById('success');
    const fail = document.getElementById('fail');
    const successMessage = document.getElementById('success-message');
    const failMessage = document.getElementById('fail-message');

    // 按钮点击事件
    seckillBtn.addEventListener('click', async () => {
        try {
            // 禁用按钮，防止重复点击
            seckillBtn.disabled = true;
            seckillBtn.textContent = '处理中...';

            // 显示加载状态
            statusMessage.classList.add('hidden');
            loading.classList.remove('hidden');
            success.classList.add('hidden');
            fail.classList.add('hidden');

            // 发起秒杀请求
            const response = await fetch(`/api/seckill?userId=${userId}&goodsId=${goodsId}`, {
                method: 'POST'
            });

            const result = await response.json();

            if (result.success) {
                // 秒杀请求成功，获取令牌并建立SSE连接
                const token = result.data;
                setupSseConnection(token);
            } else {
                // 秒杀请求失败（如已抢完）
                showFail(result.message);
            }
        } catch (error) {
            console.error('秒杀请求失败:', error);
            showFail('网络错误，请重试');
        }
    });

    // 建立SSE连接
    function setupSseConnection(token) {
        // 浏览器原生支持的EventSource用于SSE连接
        const source = new EventSource(`/api/seckill/sse-connect?token=${token}`);

        // 监听消息事件
        source.addEventListener('seckillResult', (event) => {
            try {
                const result = JSON.parse(event.data);
                if (result.status === 'SUCCESS') {
                    showSuccess(result.message + (result.orderId ? `，订单号: ${result.orderId}` : ''));
                } else {
                    showFail(result.message);
                }
            } catch (error) {
                console.error('解析SSE消息失败:', error);
                showFail('处理失败，请重试');
            } finally {
                // 关闭SSE连接
                source.close();
            }
        });

        // 监听错误事件
        source.addEventListener('error', (error) => {
            console.error('SSE连接错误:', error);
            source.close();

            // SSE失败时降级为轮询
            startPolling(token);
        });

        // 监听超时事件
        source.addEventListener('timeout', () => {
            console.log('SSE连接超时');
            source.close();

            // 超时后降级为轮询
            startPolling(token);
        });
    }

    // 轮询降级方案
    function startPolling(token) {
        let delay = 500; // 初始延迟500ms
        const maxDelay = 3000; // 最大延迟3秒

        const poll = async () => {
            try {
                const response = await fetch(`/api/seckill/result?token=${token}`);
                const result = await response.json();

                if (result.success) {
                    const data = result.data;
                    if (data.status !== 'PROCESSING') {
                        if (data.status === 'SUCCESS') {
                            showSuccess(data.message);
                        } else {
                            showFail(data.message);
                        }
                        return; // 结束轮询
                    }
                }

                // 继续轮询，延迟递增
                delay = Math.min(delay + 500, maxDelay);
                setTimeout(poll, delay);
            } catch (error) {
                console.error('轮询失败:', error);
                // 出错后延迟重试
                setTimeout(poll, Math.min(delay + 1000, maxDelay));
            }
        };

        // 开始轮询
        poll();
    }

    // 显示成功信息
    function showSuccess(message) {
        loading.classList.add('hidden');
        success.classList.remove('hidden');
        successMessage.textContent = message;
        seckillBtn.textContent = '已抢购';
        seckillBtn.classList.remove('bg-red-500', 'hover:bg-red-600');
        seckillBtn.classList.add('bg-gray-500');
    }

    // 显示失败信息
    function showFail(message) {
        loading.classList.add('hidden');
        fail.classList.remove('hidden');
        failMessage.textContent = message;
        seckillBtn.textContent = '立即抢购';
        seckillBtn.disabled = false;
    }
</script>
</body>
</html>
